package bid.yanhj.yanhaijiang.httpurlconnection;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 *  1 创建URL对象
 *  2 设置HttpURLConection对象
 *  3 设置请求方式
 *  4 获得服务器返回的输入流
 *  5 获取输入流的额数据
 *  6 关闭连接
 *
 *  网络请求是不能在主线程里发起的 只能在子线程发起
 */
public class MainActivity extends AppCompatActivity {

    private static final String BASE_URL = "https://www.huya.com/udb_web/checkLogin.php";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 创建一个子线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                getDataFromInternet();
            }
        }).start();
    }


    public void getDataFromInternet() {

        try {
            URL url = new URL(BASE_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            InputStream inputStream = connection.getInputStream();
            StringBuffer stringBuffer = new StringBuffer();
            String line = "";
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            // 容易写错
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }

            String response = stringBuffer.toString();
            Log.d("yanhj", response);
            Log.d("yanhj", "getDataFromInternet: ");
            bufferedReader.close();
            inputStream.close();
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
